//
//  ContactsViewController.m
//  e律师
//
//  Created by 韦淋 on 2017/6/2.
//  Copyright © 2017年 test. All rights reserved.
//

#import "ContactsViewController.h"

@interface ContactsViewController ()<UITableViewDelegate,UITableViewDataSource,
UISearchBarDelegate,UISearchDisplayDelegate,ContactCellActionDelegate>

{
    NSArray *_rowArr;//row arr
    NSArray *_sectionArr;//section arr
}
@property (nonatomic, strong) UIView *barView;
@property (nonatomic, strong) UILabel *barTitleLable;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *serverDataArr;//数据源
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic,strong) UISearchBar *searchBar;//搜索框
@property (nonatomic,strong) UISearchDisplayController *searchDisplayController;//搜索VC

@end

@implementation ContactsViewController
{
    NSMutableArray *_searchResultArr;//搜索结果Arr
}

#pragma mark - dataArr(模拟从服务器获取到的数据)
- (NSArray *)serverDataArr{
    if (!_serverDataArr) {
//        [NetworkingManager getUrl:[NSString stringWithFormat:@"%@%@",CONTACTS_URL,@"id=1"] dic:nil Succeed:^(id responseData) {
//            NSLog(@"---------%@",responseData);
//            self.serverDataArr = responseData[@"result"];
//            NSLog(@"++++++%@",self.serverDataArr);
//        } failure:^(NSError *error) {
//            
//        }];
//        _serverDataArr=@[@{@"ssjg":@"1",@"name":@"1"},@{@"ssjg":@"2",@"name":@"花无缺"},@{@"ssjg":@"3",@"name":@"东方不败"},@{@"ssjg":@"4",@"name":@"任我行"},@{@"ssjg":@"5",@"name":@"逍遥王"},@{@"ssjg":@"6",@"name":@"阿离"},@{@"ssjg":@"13",@"name":@"百草堂"},@{@"ssjg":@"8",@"name":@"三味书屋"},@{@"portrait":@"9",@"name":@"彩彩"},@{@"ssjg":@"10",@"name":@"陈晨"},@{@"portrait":@"11",@"name":@"多多"},@{@"ssjg":@"12",@"name":@"峨嵋山"},@{@"portrait":@"7",@"name":@"哥哥"},@{@"ssjg":@"14",@"name":@"林俊杰"},@{@"ssjg":@"15",@"name":@"足球"},@{@"ssjg":@"16",@"name":@"58赶集"},@{@"ssjg":@"17",@"name":@"搜房网"},@{@"ssjg":@"18",@"name":@"欧弟"}];
    }
    return _serverDataArr;
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
//    self.tabBarController.tabBar.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = false;
}
//- (void)viewWillDisappear:(BOOL)animated{
//    self.tabBarController.tabBar.hidden = YES;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBar_bg"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    self.dataArr=[NSMutableArray array];

    
    [self getInfo];
    
//    for (NSDictionary *subDic in self.serverDataArr) {
//        ContactModel *model=[[ContactModel alloc]initWithDic:subDic];
//        [self.dataArr addObject:model];
//    }
//    
//    _rowArr=[ContactDataHelper getFriendListDataBy:self.dataArr];
//    _sectionArr=[ContactDataHelper getFriendListSectionBy:[_rowArr mutableCopy]];
//    
//    NSLog(@"rowArr:%@",_rowArr);
//    NSLog(@"sectionArr:%@",_sectionArr);
    
    //configNav
    [self configNav];
    //布局View
    [self setUpView];
    
    _searchDisplayController=[[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
    [_searchDisplayController setDelegate:self];
    [_searchDisplayController setSearchResultsDataSource:self];
    [_searchDisplayController setSearchResultsDelegate:self];
    
    _searchResultArr=[NSMutableArray array];
}

- (void)getInfo{
    [NetworkingManager getUrl:[NSString stringWithFormat:@"%@gsid=%@",CONTACTS_URL,[InfoSingleTon personInfoSingleTon].infoDic[@"cid"]] dic:nil Succeed:^(id responseData) {
        self.serverDataArr = responseData[@"result"];
        
        NSLog(@"contacts = %@",self.serverDataArr);
        
        for (NSDictionary *subDic in self.serverDataArr) {
            ContactModel *model=[[ContactModel alloc]initWithDic:subDic];
            [self.dataArr addObject:model];
        }
        
        _rowArr=[ContactDataHelper getFriendListDataBy:self.dataArr];
        _sectionArr=[ContactDataHelper getFriendListSectionBy:[_rowArr mutableCopy]];
        
        NSLog(@"rowArr:%@",_rowArr);
        NSLog(@"sectionArr:%@",_sectionArr);
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)configNav{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0.0, 0.0, 30.0, 30.0)];
    [btn setBackgroundImage:[UIImage imageNamed:@"contacts_add_friend"] forState:UIControlStateNormal];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc]initWithCustomView:btn]];
}

#pragma mark - setUpView
- (void)setUpView{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0.0, SCREEN_HEIGHT-49.0, SCREEN_WIDTH, 49.0)];
    [imageView setImage:[UIImage imageNamed:@"footerImage"]];
    [imageView setContentMode:UIViewContentModeScaleToFill];
    [self.view insertSubview:imageView atIndex:0];
    [self.view addSubview:self.barView];
    [self.barView addSubview:self.barTitleLable];
    [self.view insertSubview:self.tableView belowSubview:imageView];
}
- (UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        [_searchBar setBackgroundImage:[UIImage imageNamed:@"ic_searchBar_bgImage"]];
        [_searchBar sizeToFit];
        [_searchBar setPlaceholder:@"搜索"];
        [_searchBar.layer setBorderWidth:0.5];
        [_searchBar.layer setBorderColor:[UIColor colorWithRed:229.0/255 green:229.0/255 blue:229.0/255 alpha:1].CGColor];
        [_searchBar setDelegate:self];
        [_searchBar setKeyboardType:UIKeyboardTypeDefault];
    }
    return _searchBar;
}
- (UIView *)barView{
    if (!_barView) {
        _barView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 64)];
        _barView.backgroundColor = [UIColor colorWithRed:63.0f/255.0f green:189.0f/255.0f blue:240.0f/255.0f alpha:1.0f];
    }
    return _barView;
}
- (UILabel *)barTitleLable{
    if (!_barTitleLable) {
        _barTitleLable = [[UILabel alloc]init];
        _barTitleLable.bounds = CGRectMake(0, 0, 200, 20);
        _barTitleLable.center = CGPointMake(self.barView.center.x, self.barView.center.y + 10);
        _barTitleLable.text = @"通讯录";
        _barTitleLable.textAlignment = NSTextAlignmentCenter;
        _barTitleLable.font = [UIFont systemFontOfSize:18];
        _barTitleLable.textColor = [UIColor whiteColor];
        
    }
    return _barTitleLable;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0.0, 64, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setSectionIndexBackgroundColor:[UIColor clearColor]];
        [_tableView setSectionIndexColor:[UIColor darkGrayColor]];
        [_tableView setBackgroundColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1]];
        _tableView.tableHeaderView=self.searchBar;
        _tableView.separatorStyle = UIAccessibilityTraitNone;
        //cell无数据时，不显示间隔线
        UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView setTableFooterView:v];
    }
    return _tableView;
}

#pragma mark - ContactCellButtonDelegate
- (void)didClickCallButtonAction:(UIButton *)sender{
    NSLog(@"打电话 ");
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"10086"];
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}
- (void)didClickTextButtonAction:(UIButton *)sender{
    NSLog(@"发短信 ");
}

#pragma mark - UITableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //section
    if (tableView==_searchDisplayController.searchResultsTableView) {
        return 1;
    }else{
        return _rowArr.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //row
    if (tableView==_searchDisplayController.searchResultsTableView) {
        return _searchResultArr.count;
    }else{
        return [_rowArr[section] count];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label) {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14.5f]];
        [label setTextColor:[UIColor grayColor]];
        [label setBackgroundColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1]];
    }
    [label setText:[NSString stringWithFormat:@"  %@",_sectionArr[section+1]]];
    return label;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (tableView!=_searchDisplayController.searchResultsTableView) {
        return _sectionArr;
    }else{
        return nil;
    }
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index-1;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView==_searchDisplayController.searchResultsTableView) {
        return 0;
    }else{
        return 22.0;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ContactDetailViewController *CDVC = [[ContactDetailViewController alloc] init];
    [self.navigationController pushViewController:CDVC animated:YES];
}
#pragma mark - UITableView dataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIde=@"cellIde";
    ContactsCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIde];
    
    if (cell==nil) {
        cell=[[ContactsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIde];
        cell.delegate = self;
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    if (tableView==_searchDisplayController.searchResultsTableView){
        [cell.infoLable setText:[_searchResultArr[indexPath.row] valueForKey:@"ssjg"]];
        [cell.nameLabel setText:[_searchResultArr[indexPath.row] valueForKey:@"name"]];
        cell.delegate = self;
    }else{
        ContactModel *model=_rowArr[indexPath.section][indexPath.row];
        cell.delegate = self;
        [cell.infoLable setText:model.ssjg];
        [cell.nameLabel setText:model.name];
    }
    
    return cell;
}

#pragma mark searchBar delegate
//searchBar开始编辑时改变取消按钮的文字
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSArray *subViews;
    subViews = [(searchBar.subviews[0]) subviews];
    for (id view in subViews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton* cancelbutton = (UIButton* )view;
            [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
            break;
        }
    }
    searchBar.showsCancelButton = YES;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //取消
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
}

#pragma mark searchDisplayController delegate
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    //cell无数据时，不显示间隔线
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [tableView setTableFooterView:v];
    
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    [self filterContentForSearchText:searchString
                               scope:[self.searchBar scopeButtonTitles][self.searchBar.selectedScopeButtonIndex]];
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
    [self filterContentForSearchText:self.searchBar.text
                               scope:self.searchBar.scopeButtonTitles[searchOption]];
    return YES;
}

#pragma mark - 源字符串内容是否包含或等于要搜索的字符串内容
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    NSMutableArray *tempResults = [NSMutableArray array];
    NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
    
    for (int i = 0; i < self.dataArr.count; i++) {
        NSString *storeString = [(ContactModel *)self.dataArr[i] name];
        NSString *storeImageString=[(ContactModel *)self.dataArr[i] ssjg]?[(ContactModel *)self.dataArr[i] ssjg]:@"";
        
        NSRange storeRange = NSMakeRange(0, storeString.length);
        
        NSRange foundRange = [storeString rangeOfString:searchText options:searchOptions range:storeRange];
        if (foundRange.length) {
            NSDictionary *dic=@{@"name":storeString,@"portrait":storeImageString};
            
            [tempResults addObject:dic];
        }
        
    }
    [_searchResultArr removeAllObjects];
    [_searchResultArr addObjectsFromArray:tempResults];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
